<?php

namespace app\model;

use app\stateData;
use think\Model;

class OrderPersonCertificateRegister extends Model
{
    /**
     * 注册证书表
     */

    protected $createTime = 'create_date';

//    protected $type = [
//        'acquisition_date' => 'datetime',
//    ];

    public function getIds()
    {
//        $list = self::select()->toArray ();
//        return array_column($list, 'id');
        return $this->column ('id');
    }

    public function personName()
    {
        return $this->hasOne(CluePerson::class, 'person_id_card', 'person_id_card')->bind(['person_name']);
    }

    public function getProjectAttr($value): array
    {
        if ($value === ''){
            return [
                'id'=>'',
                'text'=>''
            ];
        }
        return [
            'id' => (int)$value,
            'text' => stateData::$_project[$value] ?: ''
        ];
    }

    public function getCertificateBAttr($value): array
    {
        if ($value === ''){
            return [
                'id'=>'',
                'text'=>''
            ];
        }
        return [
            'id' => (int)$value,
            'text' => stateData::$_b_doc[$value] ?: ''
        ];
    }

    public function getSocialSecurityAttr($value): array
    {
        if ($value === ''){
            return [
                'id'=>'',
                'text'=>''
            ];
        }
        return [
            'id' => (int)$value,
            'text' => stateData::$_social_security[$value] ?: ''
        ];
    }

    public function getCycleAttr($value): array
    {
        $str = '';
        if (!empty($value)){
            $arr = explode(',',$value);
            foreach ($arr as $item) {
                $str .= stateData::$_cycle[$item].'/';
            }
            $str = rtrim($str,'/');
        }

        return [
            'id' => $value?:'',
            'text' => $str
        ];
    }
//
    public function getTransferAttr($value)
    {

        if($value){
            $text = stateData::$_transfer[$value] ?: '';
        }else{
            $text = '';
        }
        return [
            'id' => $value?:'',
            'text' => $text
        ];
    }
//
    public function getSocialSecurityAccStatusAttr($value): array
    {
        return [
            'id' => $value?:'',
            'text' => stateData::$_social_security_acc_status[$value] ?: ''
        ];
    }

    public function getBDocStatusAttr($value): array
    {
        return [
            'id' => $value?:'',
            'text' => stateData::$_b_doc_status[$value] ?: ''
        ];
    }

    public function getInformationFileAttr($value)
    {
        if (empty($value)) return "";
        $arr = explode(',',$value);
        $value = '';
        foreach($arr as &$v){
             $value .= config('file.url').$v .',';
        }
        return rtrim($value,',');
    }

    public function getContractFileAttr($value)
    {
        if (empty($value)) return "";
        $arr = explode(',',$value);
        $value = '';
        foreach($arr as &$v){
            $value .= config('file.url').$v .',';
        }
        return rtrim($value,',');
    }

    public function getGetUidAttr($name)
    {
        return [
            'id' => $name??'',
            'text' => (new User)->getIdNickName($name) ?: ''
        ];
    }

    public function getGetOrgAttr($name)
    {
        return [
            'id' => $name?:'',
            'text' => (new UserOrganization)->getStructureName($name) ?: ''
        ];
    }

    public function getStatusAttr($name)
    {
        if (array_key_exists($name,stateData::$_sh_status)){
            $text = stateData::$_sh_status[$name];
        }else{
            $text = '';
        }
        return [
            'id' => $name?:'',
            'text' => $text
        ];
    }
    public function getBusinessIdAttr($name)
    {
        return [
            'id' => $name,
            'text' => (new SystemBusiness)->getBusinessIdTitle($name) ?: ''
        ];
    }

    //如果自定义字段json为空 转化空json
    public function setCustomAttr($name)
    {
        if (empty($name)) $name = new \stdClass;

        return $name;
    }

    public function getCertificateLeixingAttr($name)
    {
        if ($name == 0) {
            return "";
        }
        return (new SystemCertificate)->getWhereIdCertificateModel($name) ?: '';
    }

    public function getCertificateLeibieAttr($name)
    {
        if ($name == 0) {
            return "";
        }
        return (new SystemCertificate)->getWhereIdCertificateModel($name) ?: '';
    }

    public function getCertificateDengjiAttr($name)
    {
        if ($name == 0) {
            return "";
        }
        return (new SystemCertificate)->getWhereIdCertificateModel($name) ?: '';
    }

    public function getCertificateZhuanyeAttr($name)
    {
        if ($name == 0) {
            return "";
        }
        return (new SystemCertificate)->getWhereIdCertificateModel($name) ?: '';
    }

    //绑定驳回原因
    public function getRejectTextAttr($name, $data)
    {
        if ($data['status'] < 0 || $data['certificate_characteristic_status'] < 0){
            return (new OrderLog)->getRejectModel($data['id'],$data['certificate_code']) ?: '';
        }
        return '';
    }

    public function getAcquisitionDateAttr($name)
    {
        if (empty($name) || $name=='0000-00-00 00:00:00') return "";
        return $name;
    }

    public function getCertificateCharacteristicAttr($value): array
    {
        return [
            'id' => $value?:'',
            'text' => stateData::$_certificate_characteristic[$value] ?: ''
        ];
    }

    public function getInformationFileNameAttr($name)
    {
        if (!$name) return '';
        return $name;
    }
    public function getContractFileNameAttr($name)
    {
        if (!$name) return '';
        return $name;
    }
//    public function getContractPriceAttr($name)
//    {
//        if ($name == '0.00'){
//            return '';
//        }
//        return $name;
//    }
//
//    public function getCatualPriceAttr($name)
//    {
//        if ($name == '0.00'){
//            return '';
//        }
//        return $name;
//    }

    public function getCertificateCharacteristicReviewedUidAttr($name)
    {
        if (!$name){
            return [
                'id'=>'',
                'text'=>''
            ];
        }
        return [
            'id'=>$name,
            'text'=>(new User)->getIdNickName ($name)
        ];
    }

    /**
     * 特价证书状态
     */
    public function getCertificateCharacteristicStatusAttr($name)
    {
        if (!$name){
            return [
                'id'=>'',
                'text'=>''
            ];
        }
        return [
            'id'=>$name,
            'text'=>stateData::$_certificate_status[$name]
        ];
    }

    /**
     * 添加人才注册证书订单
     * @param $param
     * @return \app\model\OrderPersonCertificateRegister|\think\Model
     */
    public function addCerRegisterModel($param)
    {
        return self::create($param);
    }

    public function editCerRegDataModel($data): OrderPersonCertificateRegister
    {
        return self::update($data);
    }

    public function getCerFindModel($cer)
    {
        $data = $this->where (['certificate_code'=>$cer])->findOrEmpty ();
        if (!$data->isEmpty ()){
            return $data->toArray ();
        }
        return '';
    }
    /**
     * 根据status查询订单
     * @param $status
     * @param $source
     * @return \app\model\OrderPersonCertificateRegister[]|array|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getWhereStatus($status, $source, $where,$whereOr,$betDate,$sort='')
    {
        //高级查询
        $db = $this->where ($where)->where(['status' => $status, 'source' => $source]);

        if (!empty ($whereOr)){
            $db->whereRaw ($whereOr);
        }
        if (!empty($betDate)){
            $db->whereRaw ($betDate);
        }

        //公示栏新加上方多选Or查询
        return $db->fetchSql(false)->order($sort)->select ()->toArray();
    }

    public function getWhereInStatusIds($status, $idArr,$source = 1)
    {
        if(empty($idArr)){
            return [];
        }

        if (is_array ($idArr)){
            $idArr = implode (',', $idArr);
        }
//        $list = $this->where(['source' => $source])
//            ->whereRaw ('get_uid IN ('.$idArr.') OR responsibility_uid IN('.$idArr.') OR certificate_characteristic_reviewed_uid IN ('.$idArr.')')
//            ->whereIn('status', $status)
//            ->order('create_date DESC')
//            ->select()->toArray();
//
//        return array_column($list, 'id');
        return $this->where(['source' => $source])
            ->whereRaw ('get_uid IN ('.$idArr.') OR responsibility_uid IN('.$idArr.') OR certificate_characteristic_reviewed_uid IN ('.$idArr.') OR submit_id IN ('.$idArr.')')
            ->whereIn('status', $status)
            ->order('create_date DESC')
            ->column ('id');
    }
    /**
     * 查询证书审核列表
     */
    //管理
    public function getWhereInStatusList($sort,$status, $ids, $accId,$pageNum,  $page = 1,$source = 1)
    {
//        if ($accId){
//            return $this->where (['id'=>$accId])->select()->toArray ();
//        }
//        return $this->where (['source'=>$source])->whereIn ('status',$status)->where('id', 'in', $ids)->page ($page,$pageNum)->order($sort)->select()->toArray ();
        if ($accId){
            return $this->where (['id'=>$accId])->order($sort)->column ('id');
        }

        return $this->where (['source'=>$source])
            ->whereIn ('status',$status)
            ->where('id', 'in', $ids)
            ->page ($page,$pageNum)
            ->order($sort)
            ->column ('id');
    }
    public function getWhereInStatusAllList($status, $ids, $accId,$source = 1)
    {
//        if ($accId){
//            return $this->where (['id'=>$accId])->select();
//        }
//        return $this->where (['source'=>$source])->whereIn ('status',$status)->where('id', 'in', $ids)->order('create_date DESC')->select();
        if ($accId) return $this->where (['id'=>$accId])->order('create_date DESC')->column ('id');

        return $this->where (['source'=>$source])
            ->whereIn ('status',$status)
            ->where('id', 'in', $ids)
            ->order('create_date DESC')
            ->column('id');
    }

    public function getWhereInDataList($status, $pageNum,  $page = 1,$source = 1)
    {
        return $this->where (['source'=>$source])->whereIn ('status',$status)->page ($page,$pageNum)->order('create_date DESC')->select();
    }
    public function getWhereCerInDataList($desc,$cer,$status, $pageNum,  $page = 1,$source = 1)
    {
        return $this->where (['source'=>$source,'certificate_id'=>$cer])->whereIn ('status',$status)->page ($page,$pageNum)->order($desc)->select();
    }


    public function getExcelList($status,$ids, $source = 1)
    {
//        return $this->where(['source' => $source])->whereIn('id',$ids)->order('create_date DESC')->select()->toArray();
        return $this->where(['source' => $source])->whereIn('id',$ids)->order('create_date DESC')->column ('id');
    }

    /**
     * @param $status
     * @param $ids
     * @param $accId //精准id 只查询等于ID的
     * @param $source
     * @return int
     * @throws \think\db\exception\DbException
     */
    public function getWhereInStatusCount($status, $ids, $accId='',$source = 1)
    {
        if ($accId){
            return $this->where(['id' => $accId])->count();
        }
        return $this->where(['source' => $source])->whereIn('status', $status)->where('id', 'in', $ids)->count();
    }
    public function getMateCount($status, $source = 1)
    {
        return $this->where(['source' => $source])->whereIn('status', $status)->count();
    }

    public function getWhereThatPersonInStatusIds($status, $id, $source = 1)
    {
        $list = $this->where(['source' => $source])
            ->where (['get_uid' => $id])
            ->whereOr ('certificate_characteristic_reviewed_uid',$id)
            ->whereOr (['submit_id'=>$id])
            ->whereOr (['responsibility_uid'=>$id])
            ->whereIn('status', $status)
            ->order('create_date DESC')
            ->field('responsibility_uid,status,id')
            ->select()->toArray();

        //删除审核人status等于已退单 已注销的
        foreach ($list as $k => $item) {
            if ($item['responsibility_uid'] == $id){
                if ($item['status']['id'] == 4 || $item['status']['id'] == 5 || $item['status']['id'] == 3){
                    unset($list[$k]);
                }
            }
        }
        return array_column(array_values ($list), 'id');
    }

    //个人
    public function getWhereThatPersonInStatusList($status,$id ,$ids ,$accId, $pageNum, $page = 1, $source = 1)
    {
//        if ($accId){
//            return $this->where (['id'=>$accId])->select ()->toArray ();
//        }
//        return $this->where (['source'=>$source])
//            ->whereIn ('status',$status)
//            ->where('id', 'in', $ids)
//            ->page ($page,$pageNum)
//            ->order('create_date DESC')
//            ->select()->toArray ();
        if ($accId){
            return $this->where (['id'=>$accId])->column ('id');
        }
        return $this->where (['source'=>$source])
            ->whereIn ('status',$status)
            ->where('id', 'in', $ids)
            ->page ($page,$pageNum)
            ->order('create_date DESC')
            ->column ('id');
    }

    public function getWhereThatPersonInStatusAllList($status,$id ,$ids ,$accId, $source = 1)
    {
//        if ($accId){
//            return $this->where (['id'=>$accId])->select ();
//        }
//        return $this->where (['source'=>$source])
//            ->whereIn ('status',$status)
//            ->where('id', 'in', $ids)
//            ->order('create_date DESC')
//            ->select();
        if ($accId){
            return $this->where (['id'=>$accId])->order('create_date DESC')->column ('id');
        }
        return $this->where (['source'=>$source])
            ->whereIn ('status',$status)
            ->where('id', 'in', $ids)
            ->order('create_date DESC')
            ->column('id');
    }

    public function getWhereThatPersonInStatusCount($status, $id, $ids,$accId, $source = 1)
    {
        if ($accId){
            return $this->where (['id'=>$accId])->count();
        }
        return $this->where(['source' => $source])
            ->where (['get_uid' => $id])
            ->whereOr (['submit_id'=>$id])
            ->whereOr(['certificate_characteristic_reviewed_uid'=>$id])
            ->whereOr (['responsibility_uid'=>$id])
            ->whereIn('status', $status)
            ->where('id', 'in', $ids)
            ->count();
    }

    /**
     * 根据id查询详情
     * @param $id
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getIdDetails($id)
    {
        $data = $this->where(['id' => $id])->findOrEmpty();
        if (!$data->isEmpty()) {
            return $data->toArray();
        }
        return null;
    }

    /**
     * 根据id删除
     * @param $id
     * @return bool
     */
    public function delId($id, $source = 2)
    {
        return self::destroy($id);
    }

    public function editId($data, $source = 2)
    {
        //编辑时候替换时间
        $data['create_date'] = date ('Y-m-d,H:i:s');
        return self::update($data);
    }

    /**
     * 通过身份证查询人才订单信息
     * @param $idcard
     * @return \app\model\CluePerson|array|mixed|\think\Model|null
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getPersonIdCardOrderModel($idcard)
    {
        $data = $this->where(['person_id_card' => $idcard])->findOrEmpty();
        if (!$data->isEmpty()) {
            return $data->toArray();
        }

        return null;
    }

    /**
     * 通过身份证|证书ID查询人才订单信息
     * @param $idcard
     * @param $cerId
     * @return array|null
     */
    public function getPersonIdCardCerOrderModel($idcard,$cerId)
    {
        $data = $this->where(['person_id_card' => $idcard,'certificate_zhuanye'=>$cerId])->findOrEmpty();
        if (!$data->isEmpty()) {
            return $data->toArray();
        }

        return null;
    }

    /**
     * 完成订单操作
     * @param $id
     * @return \app\model\OrderPersonCertificateRegister
     */
    public function completeOperateModel($idcard)
    {
        return $this->where(['person_id_card' => $idcard])->update(['status' => 5]);
    }

    /**
     * 修改人才订单为审核通过待出售
     * @param $id
     * @return \app\model\OrderPersonCertificateRegister
     */
    public function saveStatusInitModel($id): OrderPersonCertificateRegister
    {
        return $this->where(['id' => $id])->update(['status' => 1]);
    }

    public function saveStatusIdCardModel($idcard)
    {
        return $this->where(['person_id_card' => $idcard])->update(['status' => 0]);
    }

    /**
     * 修改为已退单
     * @param $idcard
     * @return \app\model\OrderPersonCertificateRegister
     */
    public function saveStatusIdCardCharModel($cerWhere,$idcard)
    {
        return $this->where(['person_id_card' => $idcard])->where ($cerWhere)->update(['status' => 4]);
    }

    /**
     * 通过人才证书id查询证书状态
     * @param $id
     * @return mixed
     */
    public function getStatusModel($id)
    {
        return $this->where(['id' => $id])->value('status');
    }

    /**
     * 通过身份证号码查询附属业务
     * @param $idCard
     * @return mixed
     */
    public function getIdCardAncillary($idCard)
    {
        return $this->where(['person_id_card' => $idCard])->value('ancillary_businesses_id');
    }

    /**
     * 通过数组id批量查询
     * @param $id
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getIdArrDataModel($id)
    {
        return $this->whereIn('id', $id)->select()->toArray();
    }

    /**
     * 通过身份证修改为已售出
     * @param $idcard
     * @param $status
     * @return \app\model\OrderPersonCertificateRegister+
     */
    public function setIdCardStatus($idcard, $status = 3)
    {
        return $this->where(['person_id_card' => $idcard])->update(['status' => $status]);
    }

    public function getPersonModel($cer)
    {
        return $this->where(['certificate_code' => $cer])->field('person_name,get_uid,get_org,catual_price,person_id_card')->select()->toArray();
    }

    /**
     * 证书到期注销 修改状态为待审核的优选证书
     * @param $idcard
     * @return \app\model\OrderPersonCertificateRegister
     */
    public function becomeLogOff($idcard)
    {
        return $this->where (['person_id_card'=>$idcard])->update (['status'=>0,'certificate_characteristic'=>2]);
    }

    /**
     * 修改为已注销
     * @param $cerWhere
     * @param $idcard
     * @return \app\model\OrderPersonCertificateRegister
     */
    public function becomeLogOffModel($cerWhere,$idcard)
    {
        return $this->where (['person_id_card'=>$idcard])->where($cerWhere)->update (['status'=>5]);
    }

    /**
     * 查询审核人为当前id的信息id集
     * @param $id
     * @return array
     */
    public function getResponsibilityUidDataModel($id)
    {
        return $this->where (['responsibility_uid'=>$id])->column ('id');
    }
    public function editResponsibilityUidDataModel($idArr,$id)
    {
        return $this->whereIn ('id',$idArr)->update (['responsibility_uid'=>$id]);
    }

    /**
     * 查询收证人员为当前id的信息id集
     * @param $id
     * @return array
     */
    public function getGetUidDataModel($id)
    {
        return $this->where (['get_uid'=>$id])->column ('id');
    }
    public function editGetUidDataModel($idArr,$id,$org)
    {
        return $this->whereIn ('id',$idArr)->update (['get_uid'=>$id,'get_org'=>$org]);
    }

    /**
     * 查询发起人为当前id的信息id集
     * @param $id
     * @return array
     */
    public function getSubmitUidDataModel($id)
    {
        return $this->where (['submit_id'=>$id])->column ('id');
    }
    public function editSubmitUidDataModel($idArr,$id)
    {
        return $this->whereIn ('id',$idArr)->update (['submit_id'=>$id]);
    }

    public function getFUidFieldDataModel($uid)
    {
        return $this->where (['responsibility_uid'=>$uid])->whereOr ('get_uid',$uid)->whereOr ('submit_id',$uid)->field('id,certificate_code,person_id_card,person_name')->select ()->toArray ();
    }

    /**
     * 获取所有数据
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getDataModel()
    {
        return $this->select ()->toArray ();
    }

    /**
     * 获取已经售卖的人才证书审核
     * @param int $status
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getFinanceFieldFindModel(int $status=3)
    {
        return $this->where(['status'=>$status])->field('certificate_code,ancillary_businesses_id')->select()->toArray ();
    }

    public function getAncillaryIdNotEmptyModel()
    {
        return $this->whereNotNull ('ancillary_businesses_id')->field('person_id_card,ancillary_businesses_id')->select()->toArray ();
    }

    /**
     * 查询今日订单个数
     * @return int
     * @throws \think\db\exception\DbException
     */
    public function getToDayCountFindModel():int
    {
        return  $this->whereDay('create_date')->count ();
    }
}